import webview
import threading
import serial
import serial.tools.list_ports
from datetime import datetime
import json

class SerialAPI:
    def __init__(self):
        self.ser = None
        self.is_connected = False
        self.received_count = 0
        self.sent_count = 0
        
    def get_available_ports(self):
        """获取可用串口列表"""
        ports = serial.tools.list_ports.comports()
        return [{"port": port.device, "description": port.description} for port in ports]
    
    def connect_serial(self, port, baudrate=9600):
        """连接串口"""
        try:
            self.ser = serial.Serial(port, baudrate, timeout=1)
            self.is_connected = True
            # 启动数据读取线程
            self.read_thread = threading.Thread(target=self._read_serial_data, daemon=True)
            self.read_thread.start()
            return {"success": True, "message": f"已连接到 {port}"}
        except Exception as e:
            return {"success": False, "message": f"连接失败: {str(e)}"}
    
    def disconnect_serial(self):
        """断开串口连接"""
        if self.ser and self.ser.is_open:
            self.ser.close()
            self.is_connected = False
        return {"success": True, "message": "串口已断开"}
    
    def send_data(self, data):
        """发送数据到串口"""
        if self.ser and self.ser.is_open:
            try:
                if isinstance(data, str):
                    data = data.encode('utf-8')
                self.ser.write(data)
                self.sent_count += 1
                return {"success": True, "message": "数据发送成功"}
            except Exception as e:
                return {"success": False, "message": f"发送失败: {str(e)}"}
        return {"success": False, "message": "串口未连接"}
    
    def get_stats(self):
        """获取统计信息"""
        return {
            "received": self.received_count,
            "sent": self.sent_count,
            "connected": self.is_connected
        }
    
    def _read_serial_data(self):
        """在后台线程中持续读取串口数据"""
        while self.is_connected and self.ser and self.ser.is_open:
            try:
                if self.ser.in_waiting > 0:
                    data = self.ser.read(self.ser.in_waiting)
                    self.received_count += 1
                    
                    # 将数据传递给前端
                    formatted_data = data.hex()
                    timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3]
                    
                    # 调用前端JavaScript函数来更新界面
                    window.evaluate_js(f'addSerialData("{timestamp}", "{formatted_data}", {len(data)})')
                    
                    # 更新统计信息
                    window.evaluate_js(f'updateStats({self.received_count}, {self.sent_count})')
                    
            except Exception as e:
                print(f"读取串口数据错误: {e}")
                break

# 创建API实例
api = SerialAPI()

# HTML界面 - 现代化炫酷设计
with open('GUI.html','r',encoding='utf-8') as file:
    html =file.read()

if __name__ == '__main__':
    window = webview.create_window(
        'CyberSerial - Web + Python 串口通信平台', 
        html=html, 
        js_api=api, 
        width=1200, 
        height=800,
        resizable=True,
        min_size=(1000, 700)
    )
    webview.start()